var createError = require("http-errors");
var express = require("express");
var path = require("path");
var cookieParser = require("cookie-parser");
const morgan = require("morgan");
var fs = require("fs");
// const logger = require('./logger')
var indexRouter = require("./routes/index");
var usersRouter = require("./routes/users");

var app = express();

// view engine setup
app.set("views", path.join(__dirname, "views"));
app.set("view engine", "pug");
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(morgan("dev"));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, "public")));

app.all("*", function (req, res, next) {
  //设置允许跨域的域名，*代表允许任意域名跨域
  res.header("Access-Control-Allow-Origin", "*");
  //允许的header类型
  res.header("Access-Control-Allow-Headers", "content-type");
  //跨域允许的请求方式
  res.header("Access-Control-Allow-Methods", "DELETE,PUT,POST,GET,OPTIONS");
  if (req.method == "OPTIONS") res.sendStatus(200);
  //让options尝试请求快速结束
  else next();
});
app.use("/", (req, res, next) => {
  res.render("index", {title: 'NodeJs'});
})
app.use("/users", usersRouter);
// catch 404 and forward to error handler
app.use(function (req, res, next) {
  next(createError(404));
});

// 输出日志到目录
var accessLogStream = fs.createWriteStream(
  path.join(__dirname, "/log/request.log"),
  { flags: "a", encoding: "utf8" }
);
// 记得要先把目录建好，不然会报错
app.use(morgan("combined", { stream: accessLogStream }));

module.exports = app;
